package com.rocky.project.action.model;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.UserDetails;

import com.opensymphony.xwork.ActionContext;
import com.rocky.project.action.base.BaseAction;
import com.rocky.project.model.admin.AdminUser;
import com.rocky.project.model.admin.Area;
import com.rocky.project.model.admin.Role;
import com.rocky.project.model.admin.UserRoleR;
import com.rocky.project.util.BeanUtil;
import com.rocky.project.util.FreemarkerUtil;
import com.rocky.project.util.WebUtil;

public class AdminUserAction extends BaseAction {
	private static final long serialVersionUID = -3510474656970657392L;
	
	private AdminUser adminUser;
	
	@SuppressWarnings("unchecked")
	public String readUser() throws Exception {			
		java.util.List<Object> paramsvalues = new LinkedList<Object>();			
//		queryHql += "  and  m.member.id =?      ";
//		paramsvalues.add(WebUtil.getSessionUser().getId());
//		String queryHql = "SELECT m.member FROM UserRoleR AS m WHERE m.deleted = false   ";
		String queryHql = "";
		String roleFilterValue = WebUtil.getParaValue("roleFilterValue");
		String memberstateFilterValue = WebUtil.getParaValue("memberstateFilterValue");
		String paytypeFilterValue = WebUtil.getParaValue("paytypeFilterValue");
		String typeFilterValue = WebUtil.getParaValue("typeFilterValue");
		String type2FilterValue = WebUtil.getParaValue("type2FilterValue");		
//		String industryMajorFilterValue = WebUtil.getParaValue("industryMajorFilterValue");		
		String keywordFilterValue  = WebUtil.getParaValue("keywordFilterValue");
		
		if(roleFilterValue!=null && ! roleFilterValue.equals("")&& ! roleFilterValue.equals("-1")){	
			queryHql = "SELECT m.member FROM AdminUser AS m WHERE m.deleted = false ";	
			queryHql += " and  m.role.id= ?     ";
			paramsvalues.add(Long.valueOf(roleFilterValue));
			
			if(memberstateFilterValue!=null && ! memberstateFilterValue.equals("")&& ! memberstateFilterValue.equals("all")){
				queryHql += " and  m.member.memberstate= ?     ";
				paramsvalues.add(memberstateFilterValue);
			}			
			if(paytypeFilterValue!=null && ! paytypeFilterValue.equals("")&& ! paytypeFilterValue.equals("all")){
				queryHql += " and  m.member.paytype= ?     ";
				paramsvalues.add(paytypeFilterValue);
			}
			if(typeFilterValue!=null && ! typeFilterValue.equals("")&& ! typeFilterValue.equals("all")){
				queryHql += " and  m.member.type= ?     ";
				paramsvalues.add(typeFilterValue);
			}
			if(type2FilterValue!=null && ! type2FilterValue.equals("")&& ! type2FilterValue.equals("all")){
				queryHql += " and  m.member.type2= ?     ";
				paramsvalues.add(type2FilterValue);
			}	

			if(keywordFilterValue!=null && ! keywordFilterValue.equals("")){				
				queryHql += " and  (m.member.keyword like ?  or m.member.username  like ? or m.member.companyname  like ?  or m.member.realname like ? )  ";
				paramsvalues.add("%"+keywordFilterValue+"%" );
				paramsvalues.add("%"+keywordFilterValue+"%" );
				paramsvalues.add("%"+keywordFilterValue+"%" );
				paramsvalues.add("%"+keywordFilterValue+"%" );
			}	
			
			queryHql += "  order by m.member.id desc   ";		
		}else{
			queryHql = "SELECT m FROM AdminUser AS m WHERE m.deleted = false   ";
			if(memberstateFilterValue!=null && ! memberstateFilterValue.equals("")&& ! memberstateFilterValue.equals("all")){
				queryHql += " and  m.memberstate= ?     ";
				paramsvalues.add(memberstateFilterValue);
			}			
			if(paytypeFilterValue!=null && ! paytypeFilterValue.equals("")&& ! paytypeFilterValue.equals("all")){
				queryHql += " and  m.paytype= ?     ";
				paramsvalues.add(paytypeFilterValue);
			}
			if(typeFilterValue!=null && ! typeFilterValue.equals("")&& ! typeFilterValue.equals("all")){
				queryHql += " and  m.type= ?     ";
				paramsvalues.add(typeFilterValue);
			}
			if(type2FilterValue!=null && ! type2FilterValue.equals("")&& ! type2FilterValue.equals("all")){
				queryHql += " and  m.type2= ?     ";
				paramsvalues.add(type2FilterValue);
			}			

			if(keywordFilterValue!=null && ! keywordFilterValue.equals("")){
				queryHql += " and  (m.keyword like ?  or m.username  like ? or m.companyname  like ?  or m.realname like ? )  ";
				paramsvalues.add("%"+keywordFilterValue+"%" );
				paramsvalues.add("%"+keywordFilterValue+"%" );
				paramsvalues.add("%"+keywordFilterValue+"%" );
				paramsvalues.add("%"+keywordFilterValue+"%" );
			}	
			queryHql += "  order by m.id desc   ";		
		}		
	
		this.pageRecords = baseService.executeHqlWithParam(queryHql,paramsvalues.toArray(),getStart(), getPageSize());
		this.rowCount = baseService.getCountHqlWithParam(queryHql, paramsvalues.toArray());		
		this.ajaxResultMap.put("rowCount", rowCount);
		this.ajaxResultMap.put("data", pageRecords);
//		this.jsonMarshaller.exclude("roleSet");//关联属性不转化	
//		this.jsonMarshaller.exclude("industryCat");//关联属性不转化
		return ajaxResult;
	}	
	@SuppressWarnings("unchecked")
	@Override
	public String createProcess() throws Exception {
		
		JSONObject obj = JSONObject.fromObject(this.jsondata);
		String username = obj.getString("username");
		String roleId = obj.getString("roleId");
		String areaId = obj.getString("areaId");
		
		obj.remove("roleId");
		obj.remove("areaId");
		obj.remove("area");		

		String queryHql = "SELECT m FROM AdminUser AS m WHERE m.deleted = false and m.username  ='" +username+"'";		
		int count = baseService.getCountHqlNoParam(queryHql);
		if(count>0){
			this.addActionMessage("很抱歉，用户名已被注册，请使用另外的用户名！");		
			return ajaxResult;
		}		
		
		adminUser = (AdminUser) JSONObject.toBean( obj, AdminUser.class );
		adminUser.setType("AdminUser");
		WebUtil.init4create(adminUser);	
		if(StringUtils.isNotEmpty(areaId)&&!areaId.equals("-1")){			
			Area area = new Area();
			area.setId(Long.valueOf(areaId));
			adminUser.setArea(area);			
		}
		baseService.create(adminUser);	
		
		if(StringUtils.isNotBlank(roleId)){
			UserRoleR userRoleR = new UserRoleR();
			Role role= new Role();
			role.setId(Long.valueOf(roleId));
			userRoleR.setRole(role);
			userRoleR.setUser(adminUser);
			baseService.create(userRoleR);	
		}
		
		return ajaxResult;		
	}	
	@SuppressWarnings("unchecked")
	@Override
	public String updateProcess() throws Exception {
		
		JSONObject obj = JSONObject.fromObject(this.jsondata);		
		String id = obj.getString("id");		
		String username = obj.getString("username");		
		String roleId = obj.getString("roleId");
		String areaId = obj.getString("areaId");		
		obj.remove("roleId");
		obj.remove("areaId");
		obj.remove("area");			

		String queryHql = "SELECT m FROM AdminUser AS m WHERE m.deleted = false and m.username  ='" +username+"' and m.id <> " + Long.valueOf(id);		
		int count = baseService.getCountHqlNoParam(queryHql);
		if(count>0){
			this.addActionMessage("很抱歉，用户名已被注册，请使用另外的用户名！");		
			return ajaxResult;
		}		
		
		adminUser = (AdminUser) JSONObject.toBean( obj, AdminUser.class );
		AdminUser adminUserDB =(AdminUser) baseService.get(AdminUser.class, Long.valueOf(id));
		
		if(StringUtils.isNotBlank(areaId)&&!areaId.equals("-1")){			
			Area area = new Area();
			area.setId(Long.valueOf(areaId));
			adminUserDB.setArea(area);			
		}else{
			adminUserDB.setArea(null);	
		}		
		if(StringUtils.isNotBlank(roleId)){
			Role role= new Role();
			role.setId(Long.valueOf(roleId));			
			this.pageRecords = baseService.executeHqlNoParam("select r  from  UserRoleR r where  r.user.id = "+Long.valueOf(id), 0, null);
			for(Iterator<UserRoleR> iter = this.pageRecords.iterator();iter.hasNext();){
				UserRoleR userRoleR =(UserRoleR) iter.next();
				baseService.deleteTrue(userRoleR);
			}			
			UserRoleR userRoleRNew = new UserRoleR();
			userRoleRNew.setRole(role);
			userRoleRNew.setUser(adminUserDB);
			baseService.create(userRoleRNew);	
		}
		BeanUtil.copyProperties(adminUser, adminUserDB);
		adminUserDB.setType("AdminUser");		
		WebUtil.init4modify(adminUserDB);			
		baseService.update(adminUserDB);
		return ajaxResult;		
	}	
	public String deleteProcess() throws Exception {
		String[] ids = WebUtil.getParaValue("ids").split(",");
		for(String id :ids){		
			baseService.delete(baseService.get(AdminUser.class, Long.valueOf(id)));
		}
		return ajaxResult;
	}
	public String acegisucess() throws Exception {
		log.info("#acegisucess#");
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (obj instanceof UserDetails) {   
		    String username = ((UserDetails)obj).getUsername();   
		    String queryHql = "FROM AdminUser AS m WHERE m.deleted = false and m.username  ='" +username+"'";	
		    Collection c = baseService.executeHqlNoParam(queryHql, 0, 10);
		    if( c==null ||  c.isEmpty()){
		    	this.addActionMessage("#acegisucess#系统发现用户状态异常，请联系管理员！"); 
		    }else{
		    	adminUser = (AdminUser)c.iterator().next();
		    	WebUtil.setSessionUser(adminUser);
		    	this.ajaxResultMap.put("id", adminUser.getId());
		    	this.ajaxResultMap.put("username", adminUser.getUsername());		    	
		    	String fromFile = "/js/resourcemenu_admin.js";
	    		queryHql = "SELECT m  FROM Resource m WHERE m.deleted = false  and m.parent is null and m.resourceType='menu' and m.status <> 'deprecated' and m.active=true  and m.fromFile ='"+fromFile+"'  order by  m.id asc ";
	    		
	    		this.pageRecords = baseService.executeHqlNoParam(queryHql, 0, null);	
		    	String json = FreemarkerUtil.getInstance().doExecute("/template/resource_menu_admin.ftl", ActionContext.getContext().getActionInvocation());
		    	this.ajaxResultMap.put("menu", json);
		    	
		    }
		} else {   
		   this.addActionMessage("#acegisucess#用户可能已经失效，请重新登陆或联系管理员！");   
		}	
		return ajaxResult;
	}	
	public String acegefailer() throws Exception {
		log.info("#acegefailer#");
		this.addActionMessage("登陆失败，请检查用户名和密码！");
		return ajaxResult;
	}	
	public String accessdenied() throws Exception {
		log.info("#accessdenied#");
		return ajaxResult;
	}	
	public String accesslogout() throws Exception {
		log.info("#accesslogout#");
		return ajaxResult;
	}		
	

}
